package com.vip.zuul.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

@Service
public class ApplicationUtils implements ApplicationContextAware{
	
	private static int port;
	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		ApplicationUtils.applicationContext = applicationContext;
	}
	
	public static Object getBean(String name) {
		return applicationContext != null?applicationContext.getBean(name):null;
	}
	
    public static ApplicationContext getApplicationContext() {  
        return applicationContext;  
    } 
    
	//通过class获取Bean.
    public static <T> T getBean(Class<T> clazz){
    	return applicationContext != null?applicationContext.getBean(clazz):null;
    }
	
	public static String getRootPath(){
		return System.getProperty("user.dir");
	}
	
	public static String getClassPathDir(){
		//return System.getProperty("java.class.path");
		return ApplicationUtils.class.getClassLoader().getResource("").getPath();
	}
	
	public static String getTMPDir(){
		//return System.getProperty("java.class.path");
		return getClassPathDir()+"tmp"+File.separator;
	}
	
	public static File getClassPathFile(String relativePath) throws FileNotFoundException{
		//File privatefile = ResourceUtils.getFile("classpath:rsa/keyprivate.txt");
		return ResourceUtils.getFile("classpath:"+relativePath);
	}
	
    public static final String getLocalIP() throws Exception {
        String ipString = "";
        Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
        InetAddress ip = null;
        while (allNetInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
            Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                ip = (InetAddress) addresses.nextElement();
                if (ip != null && ip instanceof Inet4Address && !ip.getHostAddress().equals("127.0.0.1")) {
                    return ip.getHostAddress();
                }
            }
        }
        return ipString;
    }


}
